﻿namespace TelecoSystems.Web.Services.Dashboard {
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using TelecoSystems.Web.Models;
    using TelecoSystems.Web.Models.Shared;

    /// <summary>
    /// DomainService exposing operations for data retrieval for charts in dashboard module
    /// </summary>
    [RequiresAuthentication]
    [EnableClientAccess()]
    public class DashboardDomainService : LinqToEntitiesDomainService<TelecoSystemsContainer> {
        /// <summary>
        /// Calculates count of contracts made on variants of all products
        /// Chart Independent value (x) = product, Dependent value (y) = count of contracts on product variants        
        /// </summary>
        public IQueryable<ChartPointItem> GetContractsOverProducts() {
            var q = from p in this.ObjectContext.Products
                    join c in this.ObjectContext.Contracts on p.Id equals c.Variant.ProductID into ps                    
                    select new ChartPointItem {
                        //Id is not important for us, but we give it some value anyway
                        Id = p.Id,
                        Label = p.Name,
                        Value = ps.Count()
                    };
            return q;
        }

        /// <summary>
        /// Calculates customers locations density
        /// Chart Independent value (x) = location(town), Dependent value (y) = count of customers located in that town/city
        /// </summary>
        public IQueryable<ChartPointItem> GetCustomersLocation() {
            var q = from c in this.ObjectContext.Customers
                    group c by c.AddressCity into gc
                    select new ChartPointItem {
                        //Id is not important for us, but we give it some value anyway
                        Id = (from c in gc
                             select c.Id).FirstOrDefault(),
                        Label = gc.Key,
                        IntValue = gc.Count()
                    };
            return q;
        }
    }
}